<template>
  <f-table ref="tableRef" @register="register">
    <template #header-left>
        <el-button
          @click="handleBatchDelete"
          >{{ t("deleteBatch") }}</el-button
        >
    </template>
    <template #export_status_name="{row}">
        <el-tag v-if="row.export_status===2" type="success">{{row.export_status_name}}</el-tag>
        <el-tag v-if="row.export_status===1" type="primary">{{row.export_status_name}}</el-tag>
        <el-tag v-if="row.export_status===-1" type="danger">{{row.export_status_name}}</el-tag>
    </template>

    <template #action="{ row }">
      <el-button type="primary" :disabled="row.export_status==1" link @click="handleDownload(row)">下载</el-button>
      <el-button type="primary" :disabled="row.export_status==1" link @click="handleDelete(row)">删除</el-button>
    </template>
  </f-table>
</template>

<script lang="ts" setup>
import { onMounted, ref, onBeforeUnmount } from 'vue'
import { t } from '@/lang'
import FTable, { BasicColumn, useTable } from '@/addon/htscrm/components/f-table'
import { tableColumns, tableSearchFormItems } from '@/addon/htscrm/data/system.download'
import { deleteExportApi, getExportKeyListApi, getExportListApi, getExportStatusListApi, deleteMultiApi } from '@/addon/htscrm/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { img } from '@/utils/common'

const tableRef = ref()
const { methods, register } = useTable({
    rowKey: 'id',
    searchFromItems: tableSearchFormItems(t),
    columns: tableColumns(t) as BasicColumn<IExportItem>[],
    beforeFetch: (opt) => {
        return { ...opt }
    },
    api: async (opt) => (await getExportListApi(opt)).data
})
const searchFromItems = tableSearchFormItems(t)

async function getExportStatusList () {
    const res = await getExportStatusListApi()
    searchFromItems[1].childrenComponent.children = Object.entries(res.data).map(([value, label]) => ({ value, label }))
}

async function getExportKeyList () {
    const res = await getExportKeyListApi()
    searchFromItems[0].childrenComponent.children = Object.entries(res.data).map(([value, label]) => ({ value, label }))
}

/**
* @description 下载
*/
function handleDownload (row: IExportItem) {
    // window.open(row.file_path)
    const url = img(row.file_path)
    const suffix = url.substring(url.lastIndexOf('.'), url.length)
    const a = document.createElement('a')
    a.setAttribute('download', url)
    a.setAttribute('target', '_blank')
    a.setAttribute('href', url)
    a.click()
}

/**
 * @description 批量删除
 */
async function handleBatchDelete() {
  const selection: IActivityItem[] = methods.getSelectionRows();
  if (selection.length == 0) {
    ElMessage.warning(t("deleteEmptyTips"));
    return;
  }
  const ids = selection.map((item) => item.id);
  const action = await ElMessageBox.alert(
    t("deleteBatchTips"),
    t("alert.title"),
    {
      type: "warning",
      showCancelButton: true,
      cancelButtonText: t("alert.cancel"),
      confirmButtonText: t("alert.confirm"),
    }
  );
  if (action === "confirm") {
    try {
        await deleteMultiApi({
            ids
        });

        ElMessage.success(t("deleteSuccess"));
        // 清空选项
        methods.clearSelection();
        // 重新加载数据
        methods.reload();
    } catch (error) {
        ElMessage.error(error.msg || '删除失败,请重试')
    }
  }
}

/**
 * @description 批量删除数据
 */
async function handleDelete (row: IExportItem) {
    const action = await ElMessageBox.confirm(t('deleteTips'), t('alert.title'))

    if (action === 'confirm') {
        await deleteExportApi(row.id)

        ElMessage.success(t('deleteSuccess'))
        // 清空选项
        methods.clearSelection()
        // 重新加载数据
        methods.reload()
    }
}

const timer = ref<any>(null)
function polling() {
    if (timer.value) {
        clearInterval(timer.value)
    }

    timer.value = setTimeout(async () => {
        ElMessageBox.confirm(
            '刷新页面获取最新状态?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }
        )
            .then(() => {
                methods.reload()
            })
    }, 120000)
}

onMounted(async () => {
    await getExportStatusList()
    await getExportKeyList()
    methods.setFormItems(searchFromItems)
    polling()
})

onBeforeUnmount(() => {
    if (timer.value) {
        clearTimeout(timer.value)
    }
})
</script>

<style lang="scss" scoped>
</style>
